package de.breitbeil.jbooking.util;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Calendar;

import javax.swing.JFrame;

import org.springframework.richclient.application.Application;

import de.breitbeil.jbooking.dao.IGenericDao;
import de.breitbeil.jbooking.domain.Booking;
import de.breitbeil.jbooking.ui.components.YearBookingCalendar;

public class CalendarToImage {

    public static BufferedImage writeToImage(Calendar firstDisplayedDay, String filename) throws IOException {
        // Set calender to selected year
        YearBookingCalendar calendar = new YearBookingCalendar();
        calendar.setFirstDisplayedDay(firstDisplayedDay);
        
        // Fill calendar with bookings
        IGenericDao genericDao = (IGenericDao) Application.instance().getApplicationContext().getBean("genericDao");
        for(Booking booking: genericDao.findAll(Booking.class)) {
            calendar.getMonthView().addBooking(booking);
        }
        
        // This is a dirty fix... it will make jcomponent.paint(g) draw the component
        // to an image without showing it first.
        // The right way would be to find out what needs to be initialized.
        JFrame throwaway = new JFrame();
        throwaway.add(calendar);
        throwaway.pack();

        // Save calendar to file
        return ScreenImage.createImage(calendar, filename);
    }
    
}
